﻿using System;
using System.Collections.Generic;

namespace PortableTPL
{
    public class AggregateException : Exception
    {
        readonly List<Exception> innerExceptions = new List<Exception>();

        public List<Exception> InnerExceptions
        {
            get { return innerExceptions; }
        }

        public AggregateException() : base("One or more errors occured.")
        {
        }

        public void Handle(Func<Exception, bool> predicate)
        {
            List<Exception> unhandledExceptions = new List<Exception>();
            foreach (Exception exception in innerExceptions)
            {
                if (!predicate(exception))
                {
                    unhandledExceptions.Add(exception);
                }
            }

            if (unhandledExceptions.Count > 0)
            {
                AggregateException aggregateException = new AggregateException();

                aggregateException.InnerExceptions.AddRange(unhandledExceptions);

                throw aggregateException;
            }
        }
    }
}
